<?php
/**
 * 日志中间件
 * create at 2021/04/12
 */
namespace app\common\middleware;
use helper\Logdriver;
use app\admin\model\sys\SystemLog;
use think\facade\Event;
class Log
{
    public function handle($request, \Closure $next)
    {
        $sys = getCustomSys();
        // 如果关闭日志
        if ($sys['basic']['system_log'] == 'close'){
            return $next($request);
        }
        if(config('log.channels')['file']['json'] == false || config('log.default') != 'file') {
            return $next($request);
        }
        $pathinfo = explode('/',$request->pathinfo());

        $appName = $pathinfo[0];
        $username  = '';
        if ($appName == 'admin'){
            $username = session('admin.username');
        }
        if ($appName == 'user' || $appName == 'home' || $appName == 'index'){
            $username = session('user.username');
        }
        if ($appName == 'mobile'){
            $username = session('member.username');
        }

        // 日志写入回调
        Event::listen('think\event\LogWrite', function($event) use($username,$request) {
            $param = [
                'get' => $request->get(),
                'post' => $request->post(),
                'sql' => isset($event->log['sql'])?$event->log['sql']:[],
                'error' => isset($event->log['error'])?$event->log['error']:[],
            ];
            $params = [
                'username' => $username,
                'ip' => $request->ip(),
                'host' => $request->domain(),
                'method' => $request->method(),
                'url' => $request->url(),
                'param' => json_encode($param,320)
            ];
            (new SystemLog())->createData($params);
        });


        return $next($request);
    }
}
